package com.wut.logger.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.wut.logger.annotation.Logger;
import com.wut.logger.common.LoggerContext;
import io.swagger.annotations.ApiOperation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.servlet.ServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Component
@Aspect
public class LoggerAspect {

    @Around(value = "@annotation(logger)")
    public Object aroundLogMethodPointcut(ProceedingJoinPoint pjp, Logger logger) throws Throwable {
        return handlePointcut(pjp, logger);
    }

    @Around(value = "@within(logger)")
    public Object aroundLogClassPointcut(ProceedingJoinPoint pjp, Logger logger) throws Throwable {
        return handlePointcut(pjp, logger);
    }

    private Object handlePointcut(ProceedingJoinPoint joinPoint, Logger logger) throws Throwable {
        long currentTimeMillis = System.currentTimeMillis();
        LoggerContext context = new LoggerContext();
        String description = "";
        try {
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            // 描述
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (ObjectUtil.isNotNull(method)) {
                ApiOperation annotation = method.getAnnotation(ApiOperation.class);
                description = annotation.value();
            }

            context.setClassName(className);
            context.setMethod(methodName);
            context.setRequest(paresArgs(joinPoint.getArgs()));
            Object o = joinPoint.proceed();
            context.setResponse(o);
            return o;
        } catch (Throwable e) {
            context.setException(e.getMessage());
            throw e;
        } finally {
            context.setCost(System.currentTimeMillis() - currentTimeMillis);
            log.info("{}:{}", description, JSON.toJSONString(context));
        }
    }

    private List<Object> paresArgs(Object[] args) {
        List<Object> params = new java.util.ArrayList<>(Collections.emptyList());
        if (Objects.nonNull(args)) {
            Arrays.stream(args).forEach(object -> {
                if (object instanceof MultipartFile) {
                    params.add("File:" + ((MultipartFile) object).getOriginalFilename() + ";size:" + ((MultipartFile) object).getSize());
                } else if (object instanceof ServletResponse) {
                } else {
                    params.add(object);
                }
            });
        }
        return params;
    }
}
